﻿using System.Collections.Generic;
using Internal.KuiHuaBaoDian.Services.Audio;
using UnityEngine;
using UnityEngine.AddressableAssets;

namespace KuiHuaBaoDian.Services.Audio {

    public enum AudioTriggerAction {
        None, Play, Stop, Pause, Resume,
    }

    public interface IAudioTrigger {

        IReadOnlyList<AssetReference> EventAssets { get; }
    }

    public abstract class KHBD_AudioTrigger : MonoBehaviour, IAudioTrigger, IAudioTriggerInternal {

        protected KHBD_AudioTrigger() : base() { }

        [SerializeField]
        private AssetReference[] m_EventAssets = new AssetReference[0];
        public IReadOnlyList<AssetReference> EventAssets => m_EventAssets;
        void IAudioTriggerInternal.SetEventAssets(AssetReference[] eventAssets) {
            m_EventAssets = eventAssets;
        }

        [SerializeField]
        private AudioTriggerAction m_OnStart;

        [SerializeField]
        private AudioTriggerAction m_OnEnable;

        [SerializeField]
        private AudioTriggerAction m_OnDisable;

        [SerializeField]
        private AudioTriggerAction m_OnDestroy;

        private bool m_IsDestroy = false;

        private bool m_IsStarted = false;

        private void DoStart() {
            if (m_OnStart == AudioTriggerAction.Play) {
                AudioService.Instance.Play(this);
            }
        }

        private void OnEnable() {
            if (m_IsStarted) {
                DoEnable();
            }
        }

        private void DoEnable() {
            if (m_OnEnable == AudioTriggerAction.Play) {
                AudioService.Instance.Play(this);
            }
        }

        private void Update() {
            if (!m_IsStarted) {
                m_IsStarted = true;
                DoEnable();
                DoStart();
            }
        }

        private void DoDisable() {
            if (m_OnDisable == AudioTriggerAction.Play) {
                AudioService.Instance.Play(this);
            }
        }

        private void OnDisable() {
            if (m_IsStarted) {
                DoDisable();
            }
        }

        private void DoDestroy() {
            if (m_OnDestroy == AudioTriggerAction.Play) {
                AudioService.Instance.Play(this);
            }
        }

        private void OnDestroy() {
            if (m_IsStarted) {
                DoDestroy();
            }
            m_IsDestroy = true;
        }

        public void Play() {
            if (!m_IsDestroy) {
                AudioService.Instance.Play(this);
            }
        }
    }
}

namespace Internal.KuiHuaBaoDian.Services.Audio {

    public interface IAudioTriggerInternal {

        void SetEventAssets(AssetReference[] eventAssets);
    }
}